package com.xxx.system.service.impl;


import com.github.pagehelper.PageHelper;
import com.xxx.system.domain.Role;
import com.xxx.system.mapper.RoleMapper;
import com.xxx.system.query.RoleQuery;
import com.xxx.system.service.IRoleService;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
// 查询事务控制方式：设置只读 支持当前事务，如果没有当前事务，就以非事务方法执行。
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional
    public void addRole(Role role) {
        roleMapper.addRole(role);

        if (role.getPermissionids().size()>0){
            roleMapper.addRoleAndPs(role);
        }

        if (role.getMenuids().size()>0){
            roleMapper.addRoleAndMs(role);
        }
    }

    @Override
    @Transactional
    public void updateRole(Role role) {
        roleMapper.updateRole(role);

        roleMapper.delRoleAndPs(role.getId());
        roleMapper.delRoleAndMs(role.getId());

        if (role.getPermissionids().size()>0){
            roleMapper.addRoleAndPs(role);
        }

        if (role.getMenuids().size()>0){
            roleMapper.addRoleAndMs(role);
        }
    }

    @Override
    @Transactional
    public void deteleById(Long id) {
        roleMapper.deteleById(id);

        roleMapper.delRoleAndPs(id);
        roleMapper.delRoleAndMs(id);
    }

    @Override
    @Transactional
    public void deleteRoleByIds(Long[] ids) {
        roleMapper.deleteRoleByIds(ids);

        for (Long id : ids) {
            roleMapper.delRoleAndPs(id);
            roleMapper.delRoleAndMs(id);
        }
    }

    @Override
    public Role findOne(Long id) {
        return roleMapper.findOne(id);
    }

    @Override
    public List<Role> findAll() {
        return roleMapper.findAll();
    }

    @Override
    public List<Role> queryPage(RoleQuery roleQuery) {
        //开始设置分页信息
        //干了三件事情：
        //1.查询总条数 2.根据驱动名称自动添加分页 3.分页查询返回结果
        PageHelper.startPage(roleQuery.getCurrentPage(), roleQuery.getPageSize());
        //直接高级查询，自动实现分页
        List<Role> roles = roleMapper.queryPage(roleQuery);//ctr 1

        //for (Role role : roles) {
        //    List<Long> permissionids=roleMapper.findPs(role.getId());
        //    role.setPermissionids(permissionids);
        //
        //    List<Long> menuids=roleMapper.findMs(role.getId());
        //    role.setMenuids(menuids);
        //}

        return roles;
    }
}
